<?php
/*
	本插件：$this->model('one688')->方法名();
	其他地方调用：model('jy_tbassistant/one688')->方法名();
*/
namespace jy_tbassistant;
defined('BY_JYA') or exit('error');
class one688 extends \plugin{
	/**
     * alibaba采集
     */
	public function get_item_one688($itemid = '', $one688url = '', $cates, $merchid = 0)
	{
		$this->alibaba($itemid, $cates, $merchid);
	}

	public function alibaba($itemid, $cates, $merchid = 0)
	{
		error_reporting(0);
		$gid=pdo_getcolumn('jy_tbassistant_catch',array('catch_source' => 'one688', 'catch_id' => $itemid),'goodsid');
		if($gid){
			exi('该商品已采集过!','error');
		}
		if (true) {
			$id = $itemid;
			$itemUrl = 'http://m.1688.com/offer/' . $id . '.html';
			$html = file_get_contents($itemUrl);

			if (preg_match('/https:\\/\\/www\\.taobao\\.com\\/markets\\/bx\\/deny_pc/', $html, $message)) {
				exi('访问被拒绝,请检查代理或VPN或请求次数过多','error');
			}

			preg_match('/window\\.wingxViewData=window\\.wingxViewData\\|\\|{};window\\.wingxViewData\\[0\\]=(.+)<\\/script>/', $html, $res);
			$json1 = $res[1];
			$json1 = json_decode($json1, true);

			if (empty($json1['detailUrl'])) {
				exi('商品获取失败','error');
			}

			$detailUrl = $json1['detailUrl'];
			$detail = cfc('http')->ihttp_get($detailUrl);
			$detail = iconv('GBK', 'UTF-8', $detail['content']);
			preg_match('/var offer_details=(.+);$/', $detail, $detailStr);
			$detail_temp = json_decode($detailStr[1], true);

			if (empty($detail_temp)) {
				preg_match('/var desc=\'(.+)\';$/', $detail, $detailStr);
				unset($detail);
				$detail['content'] = $detailStr[1];
			}
			else {
				$detail = $detail_temp;
			}

			$thumb_url = array();

			foreach ($json1['imageList'] as $k => $v) {
				$thumb_url[] =  cfc('files')->source_save($v['originalImageURI'],'image','','','',0);
			}

			$thumb = $thumb_url[0];
			unset($thumb_url[0]);
			$priceRange = explode('-', $json1['priceDisplay']);
			$minprice = floatval($priceRange[0]);
			$maxprice = empty($priceRange[1]) ? floatval($priceRange[0]) : floatval($priceRange[1]);
			$hasoption = empty($json1['skuProps']) ? 0 : 1;
			$param = $json1['productFeatureList'];
			$detail['content'] = $this->model('model')->contentpasswh($detail['content']);
			preg_match_all('/<img.*?src=[\\\\\'| \\"](.*?(?:[\\.gif|\\.jpg]?))[\\\\\'|\\"].*?[\\/]?>/', $detail['content'], $imgs);

			if (isset($imgs[1])) {
				foreach ($imgs[1] as $img) {
					$catchimg = $img;

					if (substr($catchimg, 0, 2) == '//') {
						$img = 'http://' . substr($img, 2);
					}

					$im = array('catchimg' => $catchimg, 'system' => cfc('files')->source_save($img,'image','','','',0));
					$images[] = $im;
				}
			}

			if (isset($images)) {
				foreach ($images as $img) {
					if (!empty($img['system'])) {
						if (!empty($img['system'])) {
							$detail['content'] = str_replace($img['catchimg'], $img['system'], $detail['content']);
						}
					}
				}
			}

			$detail['content'] = $this->model('model')->html_to_images($detail['content']);
			$params=array('uniacid'=>$_SESSION['uniacid'],'catch_source' => 'one688', 'catch_id' => $itemid, 'catch_url' => $catch_url);
			$data = array(
				'uniacid' => $_SESSION['uniacid'],
				'title' => $json1['subject'],
				'subtitle' => $item['subTitle'],
				'merchid' => $item['merchid'],
				'nochecked' =>  empty($merchid) ? 0 : 1,
				'total' => $json1['canBookedAmount']?:18,
				'price' => $minprice,
				'minprice' => $minprice,
				'maxprice' => $maxprice,
				'costprice' => $minprice,
				'cates' => $cates,
				'createtime' => time(),
				'updatetime' => time(),
				'isoption' => (0 < count($hasoption) ? 1 : 0),
				'status' => 0,
				'buylevels' => '',
				'showlevels' => '',
				'buygroups' => '',
				'showgroups' => '',
				'storeids' => '',
				'image' => $thumb, 
				'images' => serialize($thumb_url),
				'content' => $detail['content'],
			);
			$pcates = array();
			$ccates = array();
			$tcates = array();
			$pcateid = 0;
			$ccateid = 0;
			$tcateid = 0;

			if (is_array($cates)) 
			{
				foreach ($cates as $key => $cid ) 
				{
					$c = pdo_get('jy_weishop_goods_group',array('id' => $cid, 'uniacid' => $_SESSION['uniacid']),'parentid');
					if ($c['parentid'] == 0) {
						$pcates[] = $cid;
					}else{
						$ccates[] = $cid;
					}
					if ($key == 0) 
					{
						if ($c['parentid'] == 0) 
						{
							$pcateid = $cid;
						}else {
							$crow = pdo_get('jy_weishop_goods_group',array('id' => $cid, 'uniacid' => $_SESSION['uniacid']),'parentid');
							$pcateid = $crow['parentid'];
							$ccateid = $cid;
						}
					}
				}
			}
			$item['pcate'] = $pcateid;
			$item['ccate'] = $ccateid;
			$item['tcate'] = $tcateid;
			if (!(empty($cates))) 
			{
				$item['cates'] = implode(',', $cates);
			}
			$item['pcates'] = implode(',', $pcates);
			$item['ccates'] = implode(',', $ccates);
			$item['tcates'] = implode(',', $tcates);
			pdo_insert('jy_weishop_goods', $data);
			$goodsid = pdo_insertid();
			$params['goodsid']=$goodsid;
			pdo_insert('jy_tbassistant_catch', $params);

			if (empty($goodsid)) {
				exi('抓取失败','error');
			}

			$param = $this->model('model')->paramFormat($param, $goodsid);

			if ($hasoption) {
				foreach ($json1['skuProps'] as $k => $v) {
					$spec = $v['prop'];
					pdo_insert('jy_weishop_goods_spec', array('uniacid' => $_SESSION['uniacid'], 'goodsid' => $goodsid, 'title' => $spec));
					$specId = pdo_insertid();

					foreach ($v['value'] as $key => $val) {
						$thumb = $val['imageUrl'];
						$title = $val['name'];
						pdo_insert('jy_weishop_goods_spec_item', array('specid' => $specId, 'title' => $val['name'], 'thumb' => empty($thumb) ? '' : $thumb));
						$specs = pdo_insertid();
						$specsid[$k][$key][$title] = $specs;
					}
				}

				$map = $json1['skuMap'];

				foreach ($map as $k => $v) {
					$specArr = explode('&gt;', $k);

					foreach ($specsid as $key => $item) {
						foreach ($item as $v1) {
							if (!empty($v1[$specArr[$key]])) {
								$sss[] = $v1[$specArr[$key]];
							}
						}
					}

					$option['specs'] = implode('_', $sss);
					unset($sss);
					$option['title'] = str_replace('&gt;', '+', $k);

					if (!empty($v['price'])) {
						$option['price'] = $v['price'];
					}
					else if (!empty($v['discountPrice'])) {
						$option['price'] = $v['discountPrice'];
					}
					else if (!empty($json1['discountPriceRanges'])) {
						$option['price'] = $json1['discountPriceRanges'][0]['price'];
					}
					else {
						$option['price'] = 0;
					}

					$option['stock'] = $v['canBookCount'];
					$option['goodsid'] = $goodsid;

					pdo_insert('jy_weishop_goods_option', $option);
				}
			}
			return array('result' => '1', 'goodsid' => $goodsid);
		}
	}

}
?>